package jjn.round2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jiang Jining
 * @since 2023-04-29 9:11
 */
public class LeetCode2423_RemoveWordToEqualFrequency {
    public boolean equalFrequency(String word) {
        Map<Character, Integer> map = new HashMap<>();
        for (Character character : word.toCharArray()) {
            Integer count = map.getOrDefault(character, 0);
            count++;
            map.put(character, count);
        }
        List<Integer> values = new ArrayList<>(map.values());
        if (values.size() <= 1) {
            return true;
        }
        values.sort(Integer::compareUnsigned);
        if (removeMin(values)) {
            return true;
        }
        return removeMax(values);
    }
    
    private boolean removeMin(List<Integer> values) {
        Integer first = values.get(0);
        int comparator = (first == 1) ? values.get(1) : first - 1;
        for (int i = 1; i < values.size(); i++) {
            if (values.get(i) != comparator) {
                return false;
            }
        }
        return true;
    }
    
    private boolean removeMax(List<Integer> values) {
        Integer last = values.get(values.size() - 1);
        int comparator = (last == 1) ? values.get(values.size() - 1) : last - 1;
        for (int i = 0; i < values.size() - 1; i++) {
            if (values.get(i) != comparator) {
                return false;
            }
        }
        return true;
    }
}
